package com.exam.commonbiz.base;

import android.app.Application;
import android.content.Context;

import com.exam.commonbiz.bean.UserInfo;
import com.exam.commonbiz.cache.ACache;
import com.exam.commonbiz.config.ConfigSP;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;

/**
 * @Author yuexingxing
 * @time 2020/6/10
 */
public abstract class BasicApplication extends Application {

    public static BasicApplication app;

    @Override
    public void onCreate() {
        super.onCreate();
        app = this;
    }

    public String getToken() {
        return ACache.get(app).getAsString(ConfigSP.SP_TOKEN);
    }

    public void setToken(String token) {
        ACache.get(app).put(ConfigSP.SP_TOKEN, token);
    }

    public static UserInfo getUserInfo() {
        if (ACache.get(app).getAsObject(ConfigSP.SP_USER_INFO) == null) {
            ACache.get(app).put(ConfigSP.SP_USER_INFO, new UserInfo());
        }
        return (UserInfo) ACache.get(app).getAsObject(ConfigSP.SP_USER_INFO);
    }

    public static void saveUserInfo(UserInfo userInfo) {
        ACache.get(app).put(ConfigSP.SP_USER_INFO, userInfo);
    }

    /**
     * 退出登录
     */
    public static void logout() {
        saveUserInfo(new UserInfo());
        app.setToken("");
    }

    //static 代码段可以防止内存泄露
    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
//                layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);//全局设置主题颜色
                return new ClassicsHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
    }
}
